package com.infocollect.project.api.ui;


import com.infocollect.common.utils.ServletUtils;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.framework.security.service.TokenService;
import com.infocollect.project.api.entity.TappDeptEntity;
import com.infocollect.project.api.entity.TappOrganEntity;
import com.infocollect.project.api.helper.CurrentHelp;
import com.infocollect.project.api.helper.JSONUtil;
import com.infocollect.project.api.helper.MapHelper;
import com.infocollect.project.api.service.ITappDeptService;
import com.infocollect.project.api.service.ITappOrganService;
import com.infocollect.project.api.vo.CurrentUserInfoVO;
import com.infocollect.project.api.vo.OrganSearchVO;
import com.infocollect.project.form.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (TappDept)表控制层
 *
 * @author makejava
 * @since 2019-12-25 10:32:28
 */
@Api(value = "tappDept", tags = "部门信息")
@RestController
@RequestMapping("tappDept")
public class TappDeptController {
    @Autowired
    private TokenService tokenService;
    /**
     * 服务对象
     */
    @Resource
    private ITappDeptService tappDeptService;
    /**
     * 服务对象
     */
    @Resource
    private ITappOrganService tappOrganService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("获取部门信息")
    @PostMapping("selectOne/{id}")
    @ResponseBody
    public R<Object> selectOne(@PathVariable(name = "id") Long id) throws IOException {

        return R.newOk(this.tappDeptService.queryById(id));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("删除部门信息")
    @PostMapping("del/{id}")
    @ResponseBody
    public R<Object> Delete(@PathVariable(name = "id") Long id) throws IOException {
        R<Object> result = new R<>();
        TappDeptEntity tappDept = new TappDeptEntity();
        tappDept.setFparentid(id);
        if (this.tappDeptService.queryAll(tappDept).size() > 0) {
            return R.newError("请先移除子部门！");
        } else {
            if (this.tappDeptService.deleteById(id)) {
                return R.newOk("操作成功！");
            } else {
                return R.newError("操作失败！");
            }
        }
    }

    /**
     * 保存机构信息
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("保存部门信息")
    @PostMapping("SaveDept")
    @ResponseBody
    public R<Object> SaveDept(@RequestBody Map<String, String> param) throws IOException {
        if (param.get("fdeptname") == null || param.get("fdeptname").length() == 0) {
            return R.newError("部门名称不能为空!");
        }
        if (param.get("forderindex") == null) {
            return R.newError("排序不能为空!");
        }
        try {
            TappDeptEntity entity = param.get("fid") == null ? null : this.tappDeptService.queryById(Long.parseLong(param.get("fid")));
//            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
            if (entity == null) {
                entity = new TappDeptEntity();
                entity.setFcreateby(currentUserInfo.getUserName());
                entity.setFlastupdateby(currentUserInfo.getUserName());
                entity.setFcreationdate(new Date());
                entity.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(entity, param);
                System.out.println(JSONUtil.objToJson(entity));
                entity.setFdeptcode(GetDeptCode(entity.getFparentid(), entity.getForganid()));
                entity.setFnum(0);
                entity.setFstate("1");
                entity = this.tappDeptService.insert(entity);

            } else {
                entity.setFlastupdateby(currentUserInfo.getUserName());
                entity.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(entity, param);
                entity = this.tappDeptService.update(entity);
            }
            return R.newOk(entity);
        } catch (Exception ex) {
            return R.newError("保存报错！具体错误信息为：" + ex);
        }
    }

    String GetDeptCode(Long pid, Long orgid) {
        //   System.out.println("获取DeptCode1");
        if (orgid != null) {
            //  System.out.println("获取DeptCode1orgid");
            TappOrganEntity entity = this.tappOrganService.queryById(orgid);
            entity.setFdeptnum((entity.getFdeptnum() == null ? 0 : entity.getFdeptnum()) + 1);
            String code = "";
            for (int i = 0; i < 5 - entity.getFdeptnum().toString().length(); i++) {
                code = code + "0";
            }
            this.tappOrganService.update(entity);
            return entity.getForgancode() + "D" + code + entity.getFdeptnum().toString();
        }
        if (pid != null) {
            TappDeptEntity entity = this.tappDeptService.queryById(pid);
            entity.setFnum((entity.getFnum() == null ? 0 : entity.getFnum()) + 1);
            String code = "";
            for (int i = 0; i < 5 - entity.getFnum().toString().length(); i++) {
                code = code + "0";
            }
            this.tappDeptService.update(entity);
            return entity.getFdeptcode() + code + entity.getFnum().toString();

        }
        return "";
    }

    @ApiOperation("部门选择")
    @PostMapping("SelectDept/{Search}")
    @ResponseBody
    public R<List<OrganSearchVO>> SelectDept(@PathVariable(name = "Search") String search) throws Exception {

        List<OrganSearchVO> searchList = new ArrayList<>();
        List<TappOrganEntity> organlist = new ArrayList<>();
        List<TappDeptEntity> tappDeptList = new ArrayList<>();
        TappOrganEntity parentorganEntity = null;
        TappDeptEntity parentdeptEntity = null;
        TappDeptEntity DeptEntity = null;
        TappOrganEntity organEntity = null;
        if (search == null || search.length() == 0 || search.equals("all")) {
            TappOrganEntity tappOrgan = new TappOrganEntity();
            tappOrgan.setForgancode("10001");
            organlist = tappOrganService.queryAll(tappOrgan);
        } else {
            DeptEntity = tappDeptService.queryByCode(search);
            if (DeptEntity == null) {
                organEntity = tappOrganService.queryByCode(search);
                organlist = tappOrganService.queryByParentID(organEntity.getFid());
                TappDeptEntity tappDept = new TappDeptEntity();
                tappDept.setForganid(organEntity.getFid());
                tappDeptList = tappDeptService.queryAll(tappDept);
            } else {
                organEntity = tappOrganService.queryById(DeptEntity.getForganid());
                tappDeptList = tappDeptService.queryByParentID(DeptEntity.getFid());
                if (parentdeptEntity != null && parentdeptEntity.getFparentid() != null)
                    parentdeptEntity = tappDeptService.queryById(DeptEntity.getFparentid());
            }
        }

        if (organEntity != null && organEntity.getFparentid() != null)
            parentorganEntity = tappOrganService.queryById(organEntity.getFparentid());
        for (int i = 0; i < organlist.size(); i++) {
            TappOrganEntity ee = organlist.get(i);
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(ee.getForgancode());
            entity.setName(ee.getForganname());
            entity.setIsDept(0);
            if (organEntity != null) {
                entity.setDeptPName(organEntity.getForganname());
                entity.setDeptPNo(organEntity.getForgancode());
                if (parentorganEntity != null) {
                    entity.setGrandNo(parentorganEntity.getForgancode());
                    entity.setGrandName(parentorganEntity.getForganname());
                }
            }
            searchList.add(entity);
        }
        for (int i = 0; i < tappDeptList.size(); i++) {
            TappDeptEntity ee = tappDeptList.get(i);
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(ee.getFdeptcode());
            entity.setName(ee.getFdeptname());
            entity.setRealName(ee.getFdeptcode());
            if (DeptEntity != null) {
                entity.setDeptPNo(DeptEntity.getFdeptcode());
                entity.setDeptPName(DeptEntity.getFdeptname());
                if (DeptEntity.getFparentid() == null) {
                    entity.setGrandNo(organEntity.getForgancode());
                    entity.setGrandName(organEntity.getForganname());
                } else {
                    entity.setGrandNo(parentdeptEntity.getFdeptcode());
                    entity.setGrandName(parentdeptEntity.getFdeptname());
                }
            } else {    ////公司下直属部门
                entity.setDeptPNo(organEntity.getForgancode());
                entity.setDeptPName(organEntity.getForganname());
                if (parentorganEntity != null) {
                    entity.setGrandNo(parentorganEntity.getForgancode());
                    entity.setGrandName(parentorganEntity.getForganname());
                }
            }
            entity.setIsDept(1);
            searchList.add(entity);
        }
        return R.newOk(searchList);

    }

    @ApiOperation("部门搜索")
    @PostMapping("SearchDept/{Search}")
    @ResponseBody
    public R<List<OrganSearchVO>> SearchDept(@PathVariable(name = "Search") String search) throws Exception {
        List<OrganSearchVO> searchList = new ArrayList<>();
        List<TappDeptEntity> DeptList = tappDeptService.queryNameOrCode(search);
        for (int i = 0; i < DeptList.size(); i++) {
            TappDeptEntity ee = DeptList.get(i);
            TappOrganEntity organEntity = tappOrganService.queryById(ee.getForganid());
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(ee.getFdeptcode());
            entity.setName(ee.getFdeptname());
            entity.setRealName(ee.getFdeptcode());
            entity.setIsDept(1);
            entity.setDeptPName(organEntity.getForganname());
            entity.setDeptPNo(ee.getForganid().toString());
            searchList.add(entity);
        }
        return R.newOk(searchList);
    }
}